﻿using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using vite_core.EF_Core.EFDbcontext;
using vite_entity.Entities;
using vite_net.Common;
using vite_services;
using static vite_net.Controllers.User.EditUser.Model;

namespace vite_net.Controllers.User.EditUser
{
    internal sealed class EditUserEndpoint : Endpoint<Eequest_EditUser, Result<Response_EditUser>>
    {
        public readonly UserServices _userServices;
        public readonly ViteNetDbContext _context;

        public EditUserEndpoint(UserServices userServices, ViteNetDbContext context)
        {
            _userServices = userServices;
            _context = context;

        }

        public override void Configure()
        {
            Post("/user/edit");
            Roles("ADMIN");
        }

        public override async Task HandleAsync(Eequest_EditUser r, CancellationToken c)
        {
            var dbSet = _context.Set<SysUser>();
            var user = await dbSet.AsNoTracking().FirstOrDefaultAsync(x => x.Id == r.Id);
            if(user == null) AddError(r => r.UserName, "用户不存在!");
            ThrowIfAnyErrors();
            var sysDept = await _context.Set<SysDept>().AsNoTracking().ToListAsync();
            user.Username = r.UserName;
            user.Nickname = r.NickName;
            user.Gender = r.GenderKey == 0 ? false : true;
            user.DeptId = (int?)(sysDept.FirstOrDefault(x => x.Code == r.DeptCode)?.Id);
            user.Avatar = r.Avatar;
            user.Mobile = r.Mobile;
            user.Status = r.Status == 0 ? false : true;
            user.Email = r.Email;
            user.UpdateTime = DateTime.Now;
            user.UpdateBy = 1;
            user.IsDeleted = false;
            dbSet.Attach(user).State = EntityState.Modified;
            await _context.SaveChangesAsync();


            await SendAsync(Result<Response_EditUser>.Ok(new Model.Response_EditUser() { 
                Code = 1,
                Msg = "一切ok"
            }));

        }
    }
}
